package cn.zwx.starter;

import cn.zwx.exception.InitException;
import cn.zwx.service.SegmentService;
import cn.zwx.service.SnowflakeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author zhangwenxue
 */
@Configuration
@EnableConfigurationProperties(DistributedIdSpringBootProperties.class)
public class DistributedIdSpringBootStarterAutoConfigure {
    private Logger logger = LoggerFactory.getLogger(DistributedIdSpringBootStarterAutoConfigure.class);
    @Resource
    private DistributedIdSpringBootProperties properties;

    @Bean
    @ConditionalOnProperty(prefix = "distributed.id.segment",name = "enable",matchIfMissing = true,havingValue = "true")
    public SegmentService initLeafSegmentStarter() throws Exception {
        DistributedIdSpringBootProperties.Segment segment = properties.getSegment();
        if (properties != null && segment != null && segment.isEnable()) {

            return new SegmentService(segment.getUrl(), segment.getUsername(),segment.getPassword());
        }
        logger.error("init leaf segment ignore properties is {}", properties);
        return null;
    }

    @Bean
    @ConditionalOnProperty(prefix = "distributed.id.snowflake",name = "enable",matchIfMissing = true,havingValue = "true")
    public SnowflakeService initLeafSnowflakeStarter() throws InitException {
        if (properties != null && properties.getSnowflake() != null && properties.getSnowflake().isEnable()) {
            DistributedIdSpringBootProperties.Snowflake snowflake = properties.getSnowflake();
            return new SnowflakeService(snowflake.getZkPath(), snowflake.getPort(),snowflake.getConnectionTimeoutMs(),
                    snowflake.getSessionTimeoutMs());
        }
        logger.error("init leaf snowflake ignore properties is {}", properties);
        return null;
    }
}
